import VuiElement from '../../base/element';
import VuiText from '../../components/text';
import SelectorTextItem from './text.item';

export default class SelectionItem extends VuiElement {
  constructor(itemName, removeHandler) {
    super();
    this._className = {
      container: 'vui-dropdown-item-container vui-selection-item',
      title: 'vui-dropdown-item-title',
      slected: 'selected'
    };
    this.option = itemName || {};
    this._actions = {
      removeHandler
    };
  }

  init() {
    const cls = this._className;
    this.initContainer();
    const title = VuiText.newInstance(this.option.text, cls.title);
    const removeHandler = this._actions.removeHandler;
    this.append(title);
    const action = evt => {
      const canRemove = removeHandler(this.option.value);
      if (canRemove) {
        this.removeSelected();
      }

      evt.stopPropagation();
    };
    this.textItem = new SelectorTextItem(this.option.text, action).init();
    return this;
  }

  setSelected() {
    this.selected = true;
    this.addClass(this._className.slected);
  }

  removeSelected() {
    this.selected = false;
    const elt = this.textItem.container;
    elt.parentElement?.removeChild(elt);
    this.removeClass(this._className.slected);
  }
}
